/*
 * Wonders tree JS Library 
 * Copyright (c) 2003-2007 Wonders Information Co.,Ltd. All Rights Reserved.
 * Ext 2.0 including override method
 */

/**
 * @ignore
 * Support MultiSelection of Tree Node by Checkbox instead
 */
var treeWidth;
Ext.tree.MultiSelectionModelEx = function(config) {
//	this.selNodes = [];
//	this.selMap = {};
//	this.addEvents(
			/**
			 * @event selectionchange Fires when the selected nodes change
			 * @param {MultiSelectionModel}
			 *            this
			 * @param {Array}
			 *            nodes Array of the selected nodes
			 */
//			"selectionchange");
//	Ext.apply(this, config);
	Ext.tree.MultiSelectionModelEx.superclass.constructor.call(this);
};

Ext.extend(Ext.tree.MultiSelectionModelEx, Ext.tree.MultiSelectionModel, {
	init : function(tree) {
		this.tree = tree;
		tree.getTreeEl().on("keydown", this.onKeyDown, this);
		tree.on("checkchange", this.onCheckChange, this);
		tree.getLoader().on("load", this.onNodeLoad, this);
	},

	onNodeLoad : function(treeLoader, node, response) {
		if (node.attributes.children) {
			node.expand();
		}
		if (node.attributes.checked) {
			this.select(node, null, true);
		}
		for (var i = 0; i < node.childNodes.length; i++) {
			this.onNodeLoad(treeLoader, node.childNodes[i], response);
		}
		if (!node.expanded) {
			node.collapse();
		}
	},

	onCheckChange : function(node, checked) {
		if (checked) {
			this.select(node, null, true);
		} else {
			this.unselect(node);
		}
	},

	clearSelections : function(suppressEvent) {
		var sn = this.selNodes;
		if (sn.length > 0) {
			for (var i = 0, len = sn.length; i < len; i++) {
				sn[i].ui.toggleCheck(false);
				// added
				// sn[i].ui.onCheckChange();
				sn[i].attributes.checked = sn[i].ui.checkbox.checked;
			}
			this.selNodes = [];
			this.selMap = {};
			if (suppressEvent !== true) {
				this.fireEvent("selectionchange", this, this.selNodes);
			}
		}
	},
	
	unselect : function(node) {
		if (this.selMap[node.id]) {
			// updated
			node.ui.toggleCheck(false);
			var sn = this.selNodes;
			var index = sn.indexOf(node);
			if (index != -1) {
				this.selNodes.splice(index, 1);
			}
			delete this.selMap[node.id];
			this.fireEvent("selectionchange", this, this.selNodes);
		}
	},
	/**
	 * Select a node.
	 * 
	 * @param {TreeNode}
	 *            node The node to select
	 * @param {EventObject}
	 *            e (optional) An event associated with the selection
	 * @param {Boolean}
	 *            keepExisting True to retain existing selections
	 * @return {TreeNode} The selected node
	 */
	select : function(node, e, keepExisting) {
		if (keepExisting !== true) {
			this.clearSelections(true);
		}
		if (this.isSelected(node)) {
			this.lastSelNode = node;
			return node;
		}
		this.selNodes.push(node);
		this.selMap[node.id] = node;
		// added
		node.ui.toggleCheck(true);
		this.lastSelNode = node;
		this.fireEvent("selectionchange", this, this.selNodes);
		return node;
	}
});

/**
 * @ignore
 * Tree Field Class
 */
Ext.form.TreeField = function(config) {
	config.readOnly = true;
	Ext.form.TreeField.superclass.constructor.call(this, config);
	var menu = this.menu = new Ext.menu.TreeMenu({
		multiSelect : this.multiSelect,
		queryEnable : this.queryEnable,
		queryMode : this.queryMode,
		multiSelectPos : this.multiSelectPos,
		field : this,
		minWidth : this.width,
		maxHeight : this.treeConfig.height,
		handler : this.treeConfig.beforeSelect
	});
	Ext.apply(this.menu.picker, {
		treeConfig : this.treeConfig
	});
	this.hiddenName = config.hiddenName;
	this.editable = config.editable;
	// Tree Node Attribute, used to acquire the hidden value, default is id
	this.actualValue = config.actualValue || 'id';
	this.pathMap = new Ext.util.MixedCollection();
	this.addEvents("selectionchange");

	this.hiddenField = new Ext.form.Hidden({
		name : this.hiddenName,
		id : this.hiddenName
	});
};

Ext.extend(Ext.form.TreeField, Ext.form.TriggerField, {
	/**
	 * True to allow Tree Node Multiselect, check SMType of TreePanel is
	 * necessary
	 */
	multiSelect : false,

	queryEnable : true,

	/**
	 * True to record Node Selection Status
	 */
	keepState : false,

	hiddenName : undefined,

	editable : true,
	
	/**
	 * \u67e5\u8be2\u6a21\u5f0f\uff0c\u5982\u679c\u662f'local'\u4ee3\u8868\u672c\u5730\u8282\u70b9\u67e5\u8be2,\u5982\u679c\u662f'remote'\u4ee3\u8868\u8fdc\u7a0b\u8282\u70b9\u67e5\u8be2,\u9ed8\u8ba4'local'
	 */
	queryMode : 'local',

	getHiddenValue : function() {
		return this.hiddenField.getValue();
	},

	getValue : function() {
		if(this.getHiddenValue()){
			return this.getHiddenValue();
		}
		else{
			var val = Ext.form.TreeField.superclass.getValue.call(this) || '';
			return val;
		}
	},
	setValue : function(value) {
		var tree = this.menu.picker.tree;
		var valArray = value.toString().split(',')
		var sm;
		if (this.keepState && tree
				&& !(this.multiSelect && this.pathMap.getCount() == 0)) {
			sm = tree.getSelectionModel();
			sm.clearSelections();
		}
		for (var i = 0; i < valArray.length; i++) {
			val = valArray[i].split('@');
			var path;
			if (val.length == 2) {
				path = val[0];
				value = val[1];
			} else {
				this.pathMap.find(function(o, key) {
					if (o == val) {
						path = key;
					}
				});
			}
			if (this.keepState) {
				if (this.multiSelect && tree && path) {
					var idArray = path.split(tree.pathSeparator);
					var node = tree.getNodeById(idArray[idArray.length - 1]);
					sm.select(node, null, true);
				} else if (tree && path) {
					this.setPath(path);
				}
			}
		}

		Ext.form.TreeField.superclass.setValue.call(this, value);

	},

	getPath : function() {
		return this.el.dom.path || '';
	},
	setPath : function(p) {
		this.el.dom.path = p;
	},
	menuListeners : {
		select : function(item, picker, node) {
			this.hiddenField.setValue(node.attributes[this.actualValue]);
			var v = node.text;
			var p = node.getPath();
			this.focus();
			this.setValue(p + '@' + v);
			this.pathMap.add(p, v);
			this.fireEvent("selectionchange", this,
					this.hiddenField.getValue(), v);
		},
		hide : function() {
			this.focus();
			var ml = this.menuListeners;
			this.menu.un("select", ml.select, this);
			this.menu.un("hide", ml.hide, this);
			this.menu.selectField.setValue('');
		}
	},
	isExpanded : function() {
		if (!this.menu || !this.menu.el) {
			return false;
		} else {
			return this.menu.el.isVisible();
		}
	},
	collapse : function() {
		if (!this.isExpanded())
			return;
		Ext.get(document).un('mousedown', this.collapseIf, this);
		this.menu.hide();
		this.el.focus();
		this.fireEvent('collapse', this);
	},
	collapseIf : function(e) {
		// Fix Firefox bug: scrollbar not included in div
		if (!e.within(this.wrap) && !e.within(this.menu.el)
				&& e.getTarget().id != this.menu.el.id) {
			this.collapse();
			Ext.get(document).un('mousedown', this.collapseIf, this);
		}
	},
	expand : function() {
		if (this.isExpanded() || !this.hasFocus) {
			return;
		}
		Ext.menu.MenuMgr.unregister(this.menu);
		this.menu.show(this.el, 'tl-bl'); // tl-bl?
		// Fix Bug, when using checkbox selection model
		if (this.getPath() != "") {
			this.menu.picker.tree.selectPath(this.getPath(), null);
		}
		this.el.focus();
		Ext.get(document).on('mousedown', this.collapseIf, this);
		this.fireEvent('expand', this);
	},
	scrollChildIntoView : function(exp, selNode) {
		if (selNode) {
			var elY = selNode.ui.getDDRepairXY()[1];

			var h = this.treeConfig.height;
			var r = elY - h * 2 + 26;

			this.menu.el.scroll(r < 0 ? 'top' : 'b', Math.abs(r));
		}
	},
	onTriggerClick : function() {
		// huyunming20160630设置tree自适应宽度
		treeWidth = document.getElementById(this.id+"_div").style.width;
		// --
		if (this.disabled)
			return;
		// updated by chenweijie
		if (this.menu.picker.isloaded && !this.keepState) {
			// loaded OK
			var rootNode = this.menu.picker.tree.getRootNode();
			var treeLoader = this.menu.picker.tree.getLoader();
			// For Async & Static Data (updated by gaoshang)
			this.menu.picker.tree.getSelectionModel().clearSelections();
			rootNode.reload();
		} else {
			this.menu.picker.isloaded = true;
		}
		this.menu.on(Ext.apply({}, this.menuListeners, {
			scope : this
		}));
		this.menu.picker.setValue(this.getValue());

		if (this.isExpanded()) {
			this.hasFocus = false;
			this.collapse();
		} else {
			this.hasFocus = true;
			this.expand();
		}

		// if(this.menu == null){
		// var menu = this.menu = new Ext.menu.TreeMenu({minWidth: this.width,
		// maxHeight: this.treeConfig.height, handler:
		// this.treeConfig.beforeSelect});//
		// Ext.apply(this.menu.picker, {treeConfig:this.treeConfig});
		// added by cwj
		// this.menu.picker.fireEvent('initialTree', this.menu.picker);
		// }
		// added by cwj
		// if(this.menu.picker.el != null){
		// this.menu.picker.generatorTree(this.menu.picker.el);
		// }

	},
	validateBlur : function() {
		return !this.menu || !this.menu.isVisible();
	},

	setEditable : function(value) {
		if (value == this.editable) {
			return;
		}
		this.editable = value;
		if (!value) {
			this.el.dom.setAttribute('readOnly', true);
			this.el.on('mousedown', this.onTriggerClick, this);
			this.el.addClass('x-combo-noedit');
		} else {
			this.el.dom.setAttribute('readOnly', false);
			this.el.un('mousedown', this.onTriggerClick, this);
			this.el.removeClass('x-combo-noedit');
		}
	},

	// private
	onRender : function(ct, position) {
		Ext.form.TreeField.superclass.onRender.call(this, ct, position);
		if (!this.editable) {
			this.editable = true;
			this.setEditable(false);
		}
		this.el.removeClass('x-item-readOnly');
	}
});

/**
 * @ignore
 * Popup Menu Class
 * 
 */
Ext.menu.TreeMenu = function(config) {
	Ext.menu.TreeMenu.superclass.constructor.call(this, config);
	var di = new Ext.menu.TreeItem(config);
	this.add(di);
	this.picker = di.picker;
	// add menu reference to the Picker
	this.picker.treeMenu = this;
	this.relayEvents(di, ['select']);
};
Ext.extend(Ext.menu.TreeMenu, Ext.menu.Menu, {
	render : function() {
		if (this.el)
			return;

		var el = new Ext.Layer({
			cls : 'x-menu',
			shadow : this.shadow,
			constrain : false,
			parentEl : this.parentEl || document.body,
			zindex : 15000
		});
		el.setStyle('background', '#fff');
		// replace auto by hidden
		// el.setStyle('overflow-y', 'hidden');// auto
		// el.setHeight(this.maxHeight);

		el.addKeyListener(27, this.hide, this);// esc
		this.el = el;
		this.focusEl = el.createChild({
			tag : 'a',
			cls : 'x-menu-focus',
			href : '#',
			onclick : 'return false;',
			tabIndex : '-1'
		});
		// [style:'margin-top: -10px;'] updated by gaoshang
		var ul = el.createChild({
			tag : 'ul',
			cls : 'x-menu-list',
			style : 'margin-top: 0px;'
		});

		/** 
		 * @ignore
		 * gaoshang: add ok & cancel Field update by wangkehao 
		 */
		// new feature for multiselection
		var optEl = null;
		if (this.multiSelectPos == 'bottom') {
			// this.treeMenu.ul.
			optEl = el.createChild({
				tag : 'div',
				cls : 'x-combotree-div'
			});
		} else{
			// this.tree.
			var ctTreeDiv = el.first();
			// this.tree.
			optEl = el.createChild({
				tag : 'div',
				cls : 'x-combotree-div'
			}, ctTreeDiv);
		}

		if (!optEl) {
			return;
		}
		
		
		
		if (this.multiSelect) {
			var confirmBtn = optEl.createChild({
				tag : 'input',
				type : 'button',
				cls : 'x-combotree-btn',
				value : '\u786e\u5b9a'
			});
			
			this.confirmBtn = confirmBtn;
		}
		var clearBtn = optEl.createChild({
			tag : 'input',
			type : 'button',
			cls : 'x-combotree-btn',
			value : '\u6e05\u9664'
		});
		this.clearBtn = clearBtn;
		/** 
		 * gaoshang: add ok & cancel Field  update by wangkehao 
		 */
		/** 
		 * @ignore
		 * chenweijie: add selectTextField
		 */
		var selectField = new Ext.form.TextField({
			width : 1, // this.minWidth * 2 - 15,
			minWidth : 1,
			anchor : '100%',
			// autoWidth: true,
			emptyText : '\u67e5\u627e\u8282\u70b9...'
		});
		var searchToolBar = new Ext.Toolbar({
			cls : 'top-toolbar',
			items : [' ', selectField]
		});

		if (this.queryEnable) {
			var ctTreePanel = el.first();
			el.setStyle('background-color', '#DFE8F6');
			var selectDiv = el.createChild({
				tag : 'div',
				cls : 'x-combotree-div',
				style : "padding-bottom: 3px;"
			}, ctTreePanel);
			/**
			 * @ignore
			 * var selectLabel = selectDiv.createChild({ tag : 'label', cls :
			 * 'x-form-item-label' }); var selectField = selectDiv.createChild({
			 * tag : "input", type : "text", size : "10", value : "", clsX :
			 * "x-tbar-page-number" }); selectLabel.dom.innerHTML = '\u9009\u62e9\uff1a';
			 */
			this.selectField = selectField;
			this.selectDiv = selectDiv;
			searchToolBar.render(selectDiv);
		}
		/** ************chenweijie: add selectTextField************* */

		this.items.each(function(item) {
			var li = document.createElement('li');
			li.className = 'x-menu-list-item';
			ul.dom.appendChild(li);
			item.render(li, this);
			// huyunming20160630设置tree自适应宽度
			li.style.width = (parseInt(treeWidth)+15)+"px";
			// --
		}, this);
		this.ul = ul;
		this.autoWidth();
		this.picker.on('expand', this.autoWidth, this);
		this.picker.on('collapse', this.autoWidth, this);

		// li.setStyle('overflow-y', 'auto');
		// li.setHeight(this.maxHeight);
		// add additonal style for ul
		// this.ul.setStyle('overflow-y', 'auto');//
		// this.ul.setHeight(this.maxHeight);// - ctTreeDiv.getHeight()
	},
	autoWidth : function() {
		/** updated by chenweijie start* */
		if (this.queryEnable) {
			this.selectDiv.setWidth(this.ul.first().getWidth());
			this.selectField.setWidth(this.ul.first().getWidth() - 17);
		}
		return;
		/** updated by chenweijie end* */
		if (!this.el)
			return;
		// if(Ext.isIE){
		this.el.setWidth(this.minWidth);// var t = this.el.dom.offsetWidth; //
		// force recalc
		var w = this.el.dom.scrollHeight > this.maxHeight ? 17 : 0;
		// updated by Gaoshang
		this.el.setWidth(this.el.dom.offsetWidth + this.ul.getWidth()
				+ this.el.getFrameWidth("lr") + w);
		// }
	}
});

/**
 * @ignore
 * TreeNode Adaptor Class
 */
Ext.menu.TreeItem = function(config) {
	Ext.menu.TreeItem.superclass.constructor.call(this,
			new Ext.TreePicker(config), config);
	this.picker = this.component;
	this.addEvents({
		select : true
	});
	this.picker.on('render', function(picker) {
		picker.getEl().swallowEvent('click');
	});
	// attach selet event when single selection
	if (!this.multiSelect) {
		this.picker.on('select', this.onSelect, this);
	}
};

Ext.extend(Ext.menu.TreeItem, Ext.menu.Adapter, {
	onSelect : function(picker, node) {
		if (node.id == '0')
			return false;
		this.fireEvent('select', this, picker, node);// menuListeners.select
		Ext.menu.TreeItem.superclass.handleClick.call(this);
	}
});

/**
 * @ignore
 * Tree Container Class
 */
Ext.TreePicker = function(config) {

	this.addEvents({
		/**
		 * @event initialTree \u8bbe\u7f6e\u521d\u59cb\u5316\u6811
		 * @param {Object}
		 *            This TreePicker object.
		 */
		"initialTree" : true
	});

	Ext.TreePicker.superclass.constructor.call(this, config);
	this.addEvents({
		select : true
	});
	if (this.handler) {
		this.on('select', this.handler, this.scope || this);
	}
};
Ext.extend(Ext.TreePicker, Ext.Component, {

	isloaded : false,

	setValue : function(value) {
		this.value = value;// if(this.tree) this.tree.selectPath(value,'text');
	},
	getValue : function() {
		return this.value;
	},
	createTree : function(id) {
		// \u5728\u6b64\u8fd4\u56de\u4e00\u4e2a\u6811
		/*
		 * var c = this.treeConfig; var tree = new Ext.DataTree({treeDiv: id,
		 * rootTitle: c.title, dataTag: c.dataTag, rootId: c.rootId});
		 * tree.baseParams = c.baseParams; tree.textField = false; tree.expand =
		 * c.expand; tree.rootCls = tree.cls = c.cls; tree.init(); return
		 * tree.tree;
		 */
		var Tree = Ext.tree;
		var tree = new Tree.TreePanel({// id
			el : id,
			animate : true,
			loader : new Tree.TreeLoader({
				dataUrl : 'http://extjs.com/deploy/ext-1.1/examples/tree/get-nodes.php'
			}),// c.dataTag
			enableDD : true,
			containerScroll : true
		});
		// set the root node
		var root = new Tree.AsyncTreeNode({
			text : 'Ext JS',// c.title
			draggable : false,
			id : 'source'// c.rootId
		});
		tree.setRootNode(root);
		// render the tree
		tree.render();
		root.expand();
		return tree;
	},

	onRender : function(container) {
		this.generatorTree(container);
	},

	generatorTree : function(container) {
		var me = this;
		container.setStyle('display', 'block');// inline
		//container.setStyle('height', 150);
		// container.setStyle('overflow', 'auto');
		// container.setStyle('background-color', '#E9E95A');
		// container: li ; its parent: ul
		// li \u662f tree\u6700\u5916\u5c42
		this.el = container;
		me.fireEvent('initialTree', me);
		// this.tree = this.createTree(container.dom.id);

		// chenweijie: \u7ed9\u8fd9\u9897\u6811\u52a0\u4e0a\u4e0b\u62c9\u6811\u6807\u793a
		this.tree.isCheckTree = true;

		this.tree.on('click', function(node, e) {
			me.fireEvent('select', me, node)
		});
		this.tree.on('expand', function() {
			me.fireEvent('expand')
		});
		this.tree.on('collapse', function() {
			me.fireEvent('collapse')
		});

		/** ************chenweijie: add selectTextField************* */
		if (this.queryEnable) {
		  if (this.queryMode == 'remote'){
			this.treeMenu.selectField.el.on('keydown', this.remotefilterTree, this);
		  }else{
		    this.tree.fieldHiddenPkgs = [];
			this.filter = new Ext.tree.TreeFilter(this.tree, {
				clearBlank : true,
				autoClear : true
			});
			this.treeMenu.selectField.el.on('keydown', this.filterTree, this);
		  }
		}
		/** ************chenweijie: add selectTextField************* */

		/** ************gaoshang: add ok & cancel Field  update by wangkehao************* */
		// new feature for multiselection
		if (this.multiSelect) {
			this.treeMenu.confirmBtn.on("click", function() {
				var tree = Ext.getCmp(this.tree.id);
				var nodes = tree.getSelectionModel().getSelectedNodes();
				var value = '';
				var hiddenValue = '';
				for (var i = 0; i < nodes.length; i++) {
					value += nodes[i].text + ',';
					hiddenValue += nodes[i].attributes[this.field.actualValue]
							+ ',';
					this.field.pathMap.add(nodes[i].getPath(), nodes[i].text);
				}
				value = value.substring(0, value.lastIndexOf(','));
				hiddenValue = hiddenValue.substring(0, hiddenValue
						.lastIndexOf(','));

				this.field.hiddenField.setValue(hiddenValue);
				this.field.setValue(value);

				if (this.field.isExpanded()) {
					this.field.hasFocus = false;
					this.field.collapse();
				} else {
					this.field.hasFocus = true;
					this.field.expand();
				}
				this.field.fireEvent("selectionchange", this.field,
						hiddenValue, value);

			}, this);
		}
		
		this.treeMenu.clearBtn.on("click", function() {
			Ext.getCmp(this.tree.id).getSelectionModel().clearSelections();
			
			this.field.hiddenField.setValue("");
			this.field.setValue("");

			if (this.field.isExpanded()) {
				this.field.hasFocus = false;
				this.field.collapse();
			} else {
				this.field.hasFocus = true;
				this.field.expand();
			}
			this.field.fireEvent("selectionchange", this.field,
					"", "");
			
		}, this);
		/** ************gaoshang: add ok & cancel Field  update by wangkehao ************* */
	},
	
	remotefilterTree : function(e){
	    var k = e.getKey();
		if (k != e.RETURN) {
			return;
		}
		var treePanel = this.tree;
		var text = e.target.value;
		treePanel.getLoader().baseParams.queryText = Ext.escapeRe(text);
	    treePanel.getRootNode().reload();
	},

	filterTree : function(e) {
		var k = e.getKey();
		if (k != e.RETURN) {
			return;
		}

		var treePanel = this.tree;

		var text = e.target.value;

		// chenweijie
		Ext.each(treePanel.fieldHiddenPkgs, function(n) {
			n.ui.show();
		});

		if (!text) {
			// \u4e0d\u8fc7\u6ee4 Yes
			this.filter.clear();
			return;
		}
		// step 1: get all node
		// api.expandAll();
		// \u6df1\u5ea6\u904d\u5386\u6240\u6709\u8282\u70b9\uff0c\u672a\u5c55\u5f00\u7684\u9700\u8981\u5c55\u5f00
		treePanel.getRootNode().cascade(this.expandAllLoadedNodes);

		var re = new RegExp('\\.*' + Ext.escapeRe(text), 'i');
		// \u53bb\u9664\u5f00\u5934\u5b57\u7b26\u641c\u7d22
		// var re = new RegExp('^' + Ext.escapeRe(text), 'gi');

		treePanel.fieldResultNode = [];

		this.filter.filterBy(function(n) {
			// !n.attributes.isClass \u5305\u542b\u76ee\u5f55
			// return !n.attributes.isClass;

			// \u4e4b\u524d\u53ea\u641c\u7d22\u5b50\u8282\u70b9
			// var result = n.isLeaf() && re.test(n.text);
			// \u73b0\u5728\u5305\u542b\u76ee\u5f55\u8282\u70b9
			var result = re.test(n.text);
			if (result) {
				treePanel.fieldResultNode.push(n);
			}
			// \u76ee\u5f55(\u6761\u4ef61) \u548c \u7b26\u5408\u6761\u4ef6\u7684\u8282\u70b9(\u6761\u4ef62) \u90fd\u7559\u7740
			// \u6ee1\u8db3\u6761\u4ef6\u5c31\u663e\u793a\uff0c\u5426\u5219\u9690\u85cf\u6389
			// \u76ee\u5f55\u8282\u70b9\u6216\u8005\u7b26\u5408\u6761\u4ef6\u7684\u8282\u70b9 \u90fd\u4fdd\u7559\u663e\u793a
			// TODO \u5947\u602a\u4e24\u6b21\u540c\u6837\u7684\u6b63\u5219\u8868\u8fbe\u5f0f\u4f1a\u6709\u4e0d\u540c\u7684\u7ed3\u679c
			// return !n.isLeaf() || re.test(n.text);
			return !n.isLeaf() || result;
		});
		// hide empty packages that weren't filtered
		treePanel.fieldHiddenPkgs = [];
		treePanel.getRootNode().cascade(this.filterFolderNode);
	},

	expandAllLoadedNodes : function(n) {
		// if (n.childrenRendered || n.loaded || !n.attributes.children) {
		if (n.childrenRendered || n.loaded || n.attributes.children) {
			if (!n.isExpanded()) {
				n.expand(false, false);
			}
		}
	},

	filterFolderNode : function(n) {
		// \u5fc5\u987b\u662f\u5bb9\u5668, n.ui.ctNode.offsetHeight < 3 \u5c31\u662f\u5bb9\u5668\u5143\u7d20\u6ca1\u6709\u5b50\u5143\u7d20\uff0c\u4e5f\u5c31\u662f\u8bf4\u5176\u4e0b\u9762\u5143\u7d20\u4e0d\u7b26\u5408\u8981\u6c42
		// \u5224\u65ad \u8fd9\u4e2anode\u662f\u5426\u4e3afolder, \u5e76\u4e14\u662f\u5426\u5305\u542bresultNode
		var isContained = false;
		// \u5224\u65ad\u662f\u5426\u4e3a\u6839\u8282\u70b9
		var treePanel = n.getOwnerTree();
		var rootId = treePanel.getRootNode().id;
		var isRootNood = rootId == n.id;
		// \u5224\u65ad\u8be5\u8282\u70b9\u5e95\u4e0b\uff08\u5305\u542b\u5c42\u7ea7\u5173\u7cfb\uff09\u662f\u5426\u4f1a\u5305\u542b\u7b26\u5408\u6761\u4ef6\u7684\u5b50\u8282\u70b9
		if (!n.isLeaf()) {

			for (var i = 0; i < treePanel.fieldResultNode.length; i++) {
				var pathStr = treePanel.fieldResultNode[i].getPath();
				var pathArray = pathStr.split('/');
				if (pathArray.length > 1) {
					pathArray.shift();
				}
				for (var j = 0; j < pathArray.length; j++) {
					if (n.id == pathArray[j]) {
						isContained = true;
						break;
					}
				}
				if (isContained == true) {
					break;
				}
			}
		}
		// alert('Node::' + n.text + '_\u7ed3\u679c\u8def\u5f84_' +
		// treePanel.fieldResultNode[0].getPath() + '_isContained:' +
		// isContained);
		// if(!n.isLeaf() && n.ui.ctNode.offsetHeight < 3){
		// if(!n.isLeaf() && (n.ui.ctNode.offsetHeight < 3 || !resultNode)){
		// \u8282\u70b9\u662f\u76ee\u5f55\u8282\u70b9\uff08\u6761\u4ef61\uff09\u5e76\u4e14\uff08\u8be5\u76ee\u5f55\u8282\u70b9\u4e0b\u6ca1\u6709\u5b50\u8282\u70b9\uff08\u6761\u4ef62\uff09 \u6216\u662f \u5176\u4e0b\u4e0d\u4f1a\u5305\u542b\u641c\u7d22\u7ed3\u679c\u5b50\u8282\u70b9\uff08\u6761\u4ef63\uff09\uff09 \u5e76\u4e14 \u6392\u9664\u6839\u8282\u70b9\uff08\u6761\u4ef64\uff09
		// if (!n.isLeaf() && (n.ui.ctNode.offsetHeight < 3 || !isContained) &&
		// !isRootNood) {
		// \u653e\u5bbd\u641c\u7d22\u8303\u56f4\uff0c\u53ef\u4ee5\u641c\u7d22\u76ee\u5f55\u8282\u70b9
		if (!n.isLeaf() && !isContained && !isRootNood) {
			n.ui.hide();
			treePanel.fieldHiddenPkgs.push(n);
		}
	}

});

Ext.reg('treeField', Ext.form.TreeField);

/**
 * @ignore
 * EditableTree
 */
Wonders.EditableTree.treeAddFlag = false;

/**
 * @ignore
 */
Wonders.EditableTree.edit = function(treeId) {
	Ext.getCmp(treeId+'_addButton').setDisabled(true);
    Ext.getCmp(treeId+'_delButton').setDisabled(true);
    Ext.getCmp(treeId+'_modifyButton').setDisabled(true);
    Ext.getCmp(treeId+'_saveButton').setDisabled(false);
    Ext.getCmp(treeId+'_cancelButton').setDisabled(false);
},

/**
 * @ignore
 */
Wonders.EditableTree.afterEdit = function(treeId) {
	Ext.getCmp(treeId+'_addButton').setDisabled(false);
    Ext.getCmp(treeId+'_delButton').setDisabled(false);
    Ext.getCmp(treeId+'_modifyButton').setDisabled(false);
    Ext.getCmp(treeId+'_saveButton').setDisabled(true);
    Ext.getCmp(treeId+'_cancelButton').setDisabled(true);
},

/**
 * @ignore
 */
Wonders.EditableTree.treeload = function(node,treeId) {
	var tree = Ext.getCmp(treeId);
			    
	tree.getLoader().load(node, function() {
		node.expand();
	});
},

/**
 * @ignore
 */
Wonders.EditableTree.nodeClick = function(node, formId, treeId, formLoadAction) {
	Wonders.utils.formLoad(formId,formLoadAction,{id :node.id,text :node.text},function(){return false;});
			    
	var form = Ext.getCmp(formId);
	var idField = form.getForm().findField('id');
	var tree = Ext.getCmp(treeId);
	
	var selectedNode = tree.getSelectionModel().getSelectedNode();
	if(!Ext.getCmp(treeId+'_saveButton').disabled && Wonders.EditableTree.treeAddFlag){
	    Wonders.EditableTree.treeload(selectedNode.parentNode,treeId);
	    
	    idField.getEl().dom.readOnly = true;
        idField.el.addClass('x-item-readOnly');
        
	    Wonders.EditableTree.afterEdit(treeId);
        
        Wonders.EditableTree.treeAddFlag = false;   
	}
},

/**
 * @ignore
 */
Wonders.EditableTree.addClick = function(formId , treeId) {
	var form = Ext.getCmp(formId);
	var idField = form.getForm().findField('id');
	var tree = Ext.getCmp(treeId);

	var selectedNode = tree.getSelectionModel().getSelectedNode();
	
	if (selectedNode) {
		selectedNode.expand(false, true, function() {
			form.getForm().reset();
			
			idField.getEl().dom.readOnly = false;
			idField.el.removeClass('x-item-readOnly'); 
			Wonders.EditableTree.edit(treeId);
			Wonders.EditableTree.treeAddFlag = true;	
			
			var newNode = new Ext.tree.AsyncTreeNode( {
				text : "\u65b0\u8282\u70b9",
				expanded :false,
				allowDrop :false,
				allowChildren :true,
				leaf :true
			});
			selectedNode.appendChild(newNode);
			newNode.select();
			form.getForm().findField('parentId').setValue(selectedNode.id);
		});
	}else {
		Ext.MessageBox.alert('\u63d0\u793a', '\u8bf7\u5148\u9009\u62e9\u9700\u8981\u6dfb\u52a0\u7684\u8282\u70b9!');
	}
},

/**
 * @ignore
 */
Wonders.EditableTree.delClick = function(formId,treeId,formDeleteAction) {
	var form = Ext.getCmp(formId);
	var idField = form.getForm().findField('id');
	var tree = Ext.getCmp(treeId);

	var selectedNode = tree.getSelectionModel().getSelectedNode();
	if (selectedNode) {
		if (selectedNode.id == 0) {
			Ext.MessageBox.alert('\u63d0\u793a', '\u8bf7\u9009\u62e9\u8981\u5220\u9664\u7684\u975e\u6839\u8282\u70b9!');
			return;
		}
	} else {
		Ext.MessageBox.alert('\u63d0\u793a', '\u8bf7\u9009\u62e9\u8981\u5220\u9664\u7684\u8282\u70b9!');			
		return;
	}

	form.getForm().findField('parentId').setValue(selectedNode.parentNode.id);
	
	if(selectedNode.childNodes.length!=0){
	   Ext.MessageBox.alert('\u63d0\u793a', '\u8be5\u8282\u70b9\u4e0b\u9762\u6709\u5b50\u8282\u70b9\uff0c\u4e0d\u80fd\u5220\u9664!');
	   return;
	}
	Ext.MessageBox.confirm('\u63d0\u793a', '\u786e\u5b9a\u8981\u5220\u9664\u8be5\u8282\u70b9\u5417?', function(btn, text){
          if (btn == 'yes'){
              form.getForm().doAction('submit', {
	                url : formDeleteAction,			
	                success : function(form, action) {
                         form.reset();	
                         Wonders.EditableTree.afterEdit(treeId);
                         	
                         idField.el.addClass('x-item-readOnly'); 			
                         Ext.MessageBox.alert('\u63d0\u793a', '\u5220\u9664\u6210\u529f!');
                         
                         Wonders.EditableTree.treeload(selectedNode.parentNode,treeId);
                     }
               });        
          }else{
               idField.getEl().dom.readOnly = true;
               idField.el.addClass('x-item-readOnly');
               
               Wonders.EditableTree.afterEdit(treeId);
           }
    });			
},

/**
 * @ignore
 */
Wonders.EditableTree.modifyClick = function(formId,treeId) {
    var tree = Ext.getCmp(treeId);
			    
	var selectedNode = tree.getSelectionModel().getSelectedNode();
	var form = Ext.getCmp(formId);
	if (selectedNode) {
		if (selectedNode.id == 0) {
			Ext.MessageBox.alert('\u63d0\u793a', '\u8bf7\u9009\u62e9\u8981\u4fee\u6539\u975e\u6839\u8282\u70b9!');
			return;
		}
		Wonders.EditableTree.edit(treeId);
		form.getForm().findField('parentId').setValue(selectedNode.parentNode.id);
	} else {
		Ext.MessageBox.alert('\u63d0\u793a', '\u8bf7\u9009\u62e9\u8981\u4fee\u6539\u7684\u8282\u70b9!');
	}
},

/**
 * @ignore
 */
Wonders.EditableTree.saveClick = function(formId,treeId,formAddAction,formUpdateAction) {
    var tree = Ext.getCmp(treeId);
    var url = formAddAction;
    if (!Wonders.EditableTree.treeAddFlag){
        url = formUpdateAction;
    }
    if (Wonders.utils.validateForm(formId)) {
		Ext.getCmp(formId).form.doAction('submit', {
			url : url,
			success : function(form, action) {
				var idField = form.findField('id');
				
				var selectedNode = tree.getSelectionModel().getSelectedNode();
				if (selectedNode) {
					Ext.MessageBox.alert('\u63d0\u793a', '\u4fdd\u5b58\u6210\u529f\uff01');
					form.reset();
					
					idField.getEl().dom.readOnly = true;
	                idField.el.addClass('x-item-readOnly'); 
	                
					Wonders.EditableTree.afterEdit(treeId);
	                Wonders.EditableTree.treeAddFlag = false;
				}
				selectedNode.parentNode.leaf = false;
				Wonders.EditableTree.treeload(selectedNode.parentNode,treeId);
			},
			failure : function(form, action) {
				Wonders.utils.handleError(action.response.responseText, false, false);
			}
		});
    }
},

/**
 * @ignore
 */
Wonders.EditableTree.cancelClick = function(formId,treeId,formAddAction,formUpdateAction) {
    var form = Ext.getCmp(formId);
	var idField = form.getForm().findField('id');
	var tree = Ext.getCmp(treeId);
	
	var selectedNode = tree.getSelectionModel().getSelectedNode();

	if(Wonders.EditableTree.treeAddFlag){
	   Wonders.EditableTree.treeAddFlag = false;
	   Wonders.EditableTree.treeload(selectedNode.parentNode,treeId);
	   form.getForm().findField('parentId').setValue(null);
	}		
			
	idField.getEl().dom.readOnly = true;
    idField.el.addClass('x-item-readOnly');
	
	Wonders.EditableTree.afterEdit(treeId);
}